package ln.fxspringarchetype.dialog.course;

import javafx.fxml.FXMLLoader;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogPane;
import javafx.stage.Stage;
import ln.fxspringarchetype.controller.course.AddCourseController;
import ln.fxspringarchetype.dialog.BaseFxDialog;
import ln.fxspringarchetype.model.Course;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

public class AddCourseDialog extends BaseFxDialog<Course> {

    private static final String fxml_path = "/ln/fxspringarchetype/view/course/add-course.fxml";
    private static final String window_icon_path = "/icon/add.png";
    private static final String title_text = "添加课程信息";

    private AddCourseController addCourseController;

    public AddCourseDialog() {
        super();
        setFxmlPath(fxml_path);
        setWindowIconPath(window_icon_path);
        initTitle();
        initButtons();
        initContent();
        initResultConverter();
    }

    @Override
    protected void initIcon() {
        DialogPane dialogPane = getDialogPane();
        Stage stage = (Stage) (dialogPane.getScene().getWindow());
        stage.getIcons().clear();
        stage.getIcons()
                .add(createIconImage(getWindowIconPath()));
    }

    @Override
    protected void initTitle() {
        setTitle(title_text);
    }

    @Override
    protected void initButtons() {
        DialogPane dialogPane = getDialogPane();
        List<ButtonType> buttonTypes = dialogPane.getButtonTypes();
        buttonTypes.clear();
        buttonTypes.addAll(List.of(createButtonTypes()));
    }

    @Override
    protected void initContent() {
        DialogPane dialogPane = getDialogPane();
        FXMLLoader fxmlLoader = getFxmlLoader();
        fxmlLoader.setLocation(Objects.requireNonNull(getClass().getResource(getFxmlPath())));
        try {
            dialogPane.setContent(fxmlLoader.load());
            addCourseController = fxmlLoader.getController();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initResultConverter() {
        setResultConverter(buttonType -> {
            if (buttonType.equals(ButtonType.CANCEL)) {
                return null;
            }
            return addCourseController.getCourseVO().toModel();
        });
    }
}
